/**
 * Created by XianTao on 2016/11/10
 * <p/>
 * Copyright (c) 2015-2015
 * Apache License
 * Version 2.0, January 2004
 * http://www.apache.org/licenses/
 */
package org.lego.wechat.portal;

import org.lego.handle.exception.entity.ExceptionMessage;
import org.lego.handle.exception.service.ExceptionMessageService;
import org.lego.wechat.base.WechatBaseApplication;
import org.lego.wechat.base.api.WechatIpApi;
import org.lego.wechat.base.entity.WxCorp;
import org.lego.wechat.base.service.WxCorpService;
import org.lego.wechat.portal.configuration.ConstantMessageKey;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Import;
import org.springframework.util.ObjectUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@SpringBootApplication
@Import({WechatBaseApplication.class})
public class WechatPortalApplication {
    /**
     * key为corpId:agentId，value为当前公众号对应的微信服务器ip地址列表
     */
    public static Map<String, List<String>> WECHAT_TRUE_ID_LIST = new HashMap<String, List<String>>();

    public static void main(String[] args) {
        SpringApplication.run(WechatPortalApplication.class, args);
    }

    @Bean(name = "initWechatPortalApplication")
    public InitializingBean initializingBean() {
        return new InitializingBean() {
            @Autowired
            private ExceptionMessageService exceptionMessageService;
            @Autowired
            private WxCorpService wxCorpService;
            @Autowired
            private WechatIpApi wechatIpApi;

            public void afterPropertiesSet() throws Exception {
                // 插入初始化数据
                if (ObjectUtils.isEmpty(exceptionMessageService.findOne(ConstantMessageKey.WECHAT_SYSTEM_WRONG_FROM_IP))) {
                    exceptionMessageService.saveAndFlush(new ExceptionMessage(ConstantMessageKey.WECHAT_SYSTEM_WRONG_FROM_IP, "来源ip【%s】不是微信服务器的ip地址"));
                }

                // 初始化全局变量
                List<WxCorp> wxCorpList = wxCorpService.findAll();
                if (!ObjectUtils.isEmpty(wxCorpList)) {
                    for (WxCorp wxCorp : wxCorpList) {
                        WECHAT_TRUE_ID_LIST.put(wxCorp.concatId(),
                                wechatIpApi.getWechatIpList(wxCorp.getCorpId(), wxCorp.getAgentId(), wxCorp.getCorpSecret()));
                    }
                }
            }
        };
    }
}
